<?php

namespace App\Admin\Actions;

use App\Constant\Enum;
use App\Constant\GroupApplyEnum;
use App\Models\GroupApply;
use App\Models\User;
use App\Services\Group\GroupService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;


class GroupApplyForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $applyId = $input['apply_id'] ?? 0;
        $action = $input['status'] ?? '';
        $remark = $input['remark'] ?? '';

        if (!in_array($action, [
            GroupApplyEnum::STATUS_APPROVED,
            GroupApplyEnum::STATUS_REJECTED,
        ])) {
            return response()->json([
                'code' => 400,
                'message' => '审核状态无效'
            ]);
        }

        /** @var GroupApply $groupApply */
        $groupApply = GroupApply::query()->with('user')->find($applyId);
        if (!$groupApply) {
            return response()->json([
                'code' => 400,
                'message' => '申请不存在'
            ]);
        }
        if ($groupApply->status != GroupApplyEnum::STATUS_PENDING) {
            return response()->json([
                'code' => 400,
                'message' => '请求已处理'
            ]);
        }

        DB::beginTransaction();
        try {
            if ($action == GroupApplyEnum::STATUS_APPROVED) {
                $groupApply->update([
                    'status' => $action,
                    'remark' => $remark,
                ]);
                GroupService::make($groupApply->user);
                if ($groupApply->type == GroupApplyEnum::TYPE_ADVANCED) {
                    User::query()
                        ->where([
                            'id' => $groupApply->user_id
                        ])
                        ->update([
                            'is_advanced_group' => 1,
                        ]);
                }
            } else {
                $groupApply->update([
                    'status' => $action,
                    'remark' => $remark,
                ]);
            }

            DB::commit();
            return response()->json([
                'code' => 200,
                'message' => '审核成功'
            ]);
        } catch (\Exception $exception) {
            DB::rollBack();

            return response()->json([
                'code' => 400,
                'message' => $exception->getMessage(),
            ]);
        }
    }

    public function form()
    {
        $id = $this->payload['key'];
        $this->hidden('apply_id')->value($id);
        $this->radio('status', '结果')->options([
            Enum::WITHDRAW_STATUS_APPROVED => '通过',
            Enum::WITHDRAW_STATUS_REJECTED => '拒绝',
        ])->required();
        $this->textarea('remark', '备注');
    }

    /**
     * 设置表单保存成功后执行的JS
     *
     * @return string|void
     */
    protected function savedScript()
    {
        return <<<JS
        if (data.code != 200) {
            Dcat.error(data.message);
            return false;
        }

        Dcat.success(data.message);
        Dcat.reload();

        return false;
JS;
    }

    /**
     * 设置表单保存失败后执行的JS
     *
     * @return string|void
     */
    protected function errorScript()
    {
        return <<<JS
        var errorData = JSON.parse(response.responseText);
        if (errorData) {
            if (errorData.message) {
                Dcat.error(errorData.message);
            } else {
                Dcat.error("审核结果必填");
            }
        } else {
            console.log('提交出错', response.responseText);
        }
        // 终止后续逻辑执行（默认逻辑）
        return false;
JS;
    }
}
